/*
 * 
 * 
 * 
 */
package com.hboxs.asl.dao.impl;

import com.hboxs.asl.dao.CartDao;
import com.hboxs.asl.entity.Cart;
import com.hboxs.asl.entity.Member;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.stereotype.Repository;

import javax.persistence.FlushModeType;
import javax.persistence.NoResultException;
import java.util.Date;

/**
 * Dao - 购物车
 */
@Repository("cartDaoImpl")
public class CartDaoImpl extends BaseDaoImpl<Cart, Long> implements CartDao {

    public void evictExpired() {
        String jpql = "delete from Cart cart where cart.modifyDate <= :expire";
        entityManager.createQuery(jpql).setFlushMode(FlushModeType.COMMIT).setParameter("expire", DateUtils.addSeconds(new Date(), -Cart.TIMEOUT)).executeUpdate();
    }

    @Override
    public Cart findByMember(Member member) {
        if (member == null) {
            return null;
        }
        String jpql = "select carts from Cart carts where lower(carts.member) = lower(:member)";
        try {
            return entityManager.createQuery(jpql, Cart.class).setFlushMode(FlushModeType.COMMIT).setParameter("member", member).getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }

    @Override
    public Long getTotalNumberOfGoodsInCart(Cart cart) {
        String queryString = "SELECT SUM(cartItem.quantity) FROM Cart AS cart JOIN cart.cartItems cartItem " +
                "WHERE cart=:cart ";
        Object sum = entityManager.createQuery(queryString).setParameter("cart", cart).getSingleResult();
        return (Long) sum;
    }
    
}